package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.config.WeChatConfig;
import com.ruoyi.common.core.domain.entity.EncryptedDataEntity;
import com.ruoyi.common.utils.sign.AESUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Map;

/**
 * @author ：jijinwu
 * @ClassName WeChatApiUtil
 * @date ：2024/7/17 - 20:52
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 * @description: 微信接口工具类
 **/
@Component
public class WeChatApiUtil {

    private static final Logger log = LoggerFactory.getLogger(WeChatApiUtil.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static Map<String, Object> jsonToMap(String jsonStr) throws IOException {
        return objectMapper.readValue(jsonStr, Map.class);
    }
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WeChatConfig weChatConfig;


    /**
     * 获取用户的 OpenId 和 SessionKey
     */
    public String getUserSessionKey(String code) {
        String url = weChatConfig.getWxUrl() + "/sns/jscode2session?appid=" + weChatConfig.getAppId()
                + "&secret=" + weChatConfig.getAppSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        String res =  restTemplate.getForObject(url,String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String sessionKey =  jsonObject.getString("session_key");
        return sessionKey;
    }

    /**
     * 获取访问令牌 AccessToken
     */
    public String getAccessToken() {
        String url = weChatConfig.getWxUrl() +"/cgi-bin/token?grant_type=client_credential&appid="
                + weChatConfig.getAppId() + "&secret=" + weChatConfig.getAppSecret();
        JSONObject tokenData = restTemplate.getForObject(url, JSONObject.class);
        String accessToken = "";
        if (tokenData != null) {
            accessToken =  tokenData.getString("access_token");
        }
        return accessToken;
    }

    /**
     * 获取用户手机号码
     */
    public EncryptedDataEntity getUserPhoneNumber(String accessToken, String code) {
        JSONObject requestBody = new JSONObject();
        JSONObject jsonBody = new JSONObject();
        EncryptedDataEntity encryptedDataEntity = null;
        try {
            String url = weChatConfig.getWxUrl() + "/wxa/business/getuserphonenumber?access_token=" + accessToken;

            // 创建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            requestBody.put("code", code);

            // 将请求头和请求体封装为 HttpEntity 对象
            HttpEntity<String> entity = new HttpEntity<>(requestBody.toJSONString(), headers);

            // 发送 POST 请求并获取响应
            ResponseEntity<JSONObject> response = restTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class);
            log.info("获取手机号结果:->{}",response);
            // 返回响应体中的 JSON 数据
            jsonBody = response.getBody();
            Map<String,Object> map = jsonToMap(jsonBody.toString());
            Map<String,Object> phone_info1 = (Map<String, Object>) map.get("phone_info");
            String phoneNumber = (String) phone_info1.get("phoneNumber");

            AESUtils aesUtils = new AESUtils();
            if (StringUtils.isNotEmpty(phoneNumber)){
                //对手机号进行加密处理
                String seed = RandomStringUtils.randomAlphanumeric(30);
                String iv = RandomStringUtils.randomAlphanumeric(16);
                encryptedDataEntity = aesUtils.encrypt(phoneNumber,seed,iv);
            }

        }catch (Exception e){
            log.error("获取手机号失败:",e.getMessage());
        }

        return encryptedDataEntity;
    }

}

